<?php
namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Dcat\Admin\Admin;
use Illuminate\Support\Facades\Redis;
use App\Models\Cabinet;
use App\Models\CabinetPoint;
use App\Models\CabinetLiveText;
use Illuminate\Support\Facades\DB;

class LiveTextImport implements ToCollection, WithChunkReading, WithHeadingRow
{
    protected $box;
    protected $cabinets;
    protected $points;

    public function __construct($boxId) {
        $this->box = Cabinet::find($boxId);
        $this->cabinets = Cabinet::where('pid', $boxId)->pluck('id')->toArray();
        $this->points = CabinetPoint::whereIn('cabinet_id', $this->cabinets)->pluck('alias', 'id')->toArray();
    }

    public function collection(Collection $rows)
    {   
        DB::beginTransaction();

        foreach ($rows->all() as $oneRow) {
            if (!in_array($oneRow['cabinet_id'], $this->cabinets)) {
                continue;
            }

            if (!in_array(trim($oneRow['condition']), CabinetLiveText::CONDITION)) {
                continue;
            }

            $one['project_id'] = $this->box['project_id'];
            $one['cabinet_pid'] = $this->box['id'];
            $one['cabinet_id'] = $oneRow['cabinet_id'];
            $one['point_id'] = $oneRow['point_id'];
            $one['point_alias'] = $this->points[$oneRow['point_id']];
            $one['name'] = trim($oneRow['name']);
            $one['value'] = round($oneRow['value'], 3);
            $one['condition'] = trim($oneRow['condition']);
            $one['created_at'] = date("Y-m-d H:i:s");
            $one['updated_at'] = date("Y-m-d H:i:s");

            $table = env('DB_PREFIX').CabinetLiveText::getModel()->getTable();
            DB::table($table)->insert($one);

            $textData = [
                'name' => $one['name'],
                'cond' => $one['condition'],
                'val' => $one['value'],
            ];
            CabinetLiveText::setTextCache($one['point_alias'], $textData);
        }

        DB::commit();
    }

    public function chunkSize(): int
    {
        return 3000;
    }
}